
package isv

import (
    //"fmt"
    "dhfshop/models"
	"strings"
	"errors"
	"time"
	"github.com/astaxie/beego/orm"
)

//支付参数设置原则：一个app_id最多只允许绑定两套支付参数，若缺省参数是特约商户类型，允许额外设置一套普通商户备用支付参数。
type AcPayParams struct {
	PayParamsId    int64        `orm:"column(pay_params_id);pk;auto" json:"pay_params_id" form:"pay_params_id"`
	PartnerId      int64        `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`          // 分销商ID
	CustAccount    *CustAccount `orm:"column(cust_account_id);rel(fk);on_delete(cascade)" json:"-" `  
	CustAccountId  int64        `orm:"-" json:"cust_account_id" form:"cust_account_id"`                       //公众号授权信息表ID
	//支付类型: 1未认证支付2认证后支付 9皇家支付 10yaband支付 11 superpay支付 12Usagms 13DahlPay 14 wisecashier 15 megaezgo 16 chinaums 17 oceanpay 18 qcurepay 20 hnapay 21 allinpay 22 全球仓
	PayWayId       int          `orm:"column(pay_way_id);default(1)" json:"pay_way_id" form:"pay_way_id"`     
	MchTypeId      int          `orm:"column(mch_type_id);default(1)" json:"mch_type_id" form:"mch_type_id"`  //微信支付子商户类型: 1普通商户;2特约商户3个人收款码模式(4royal5yaband)
	Name           string       `orm:"column(name);size(100);null" json:"name" form:"name"`                   //公众号公司名称
	MediaId        string       `orm:"column(media_id);null" json:"media_id" form:"media_id"`                 //个人收款二维码媒体ID
	// 缺省支付参数
	AppId          string       `orm:"column(app_id);size(32);null" json:"app_id" form:"app_id"`              //服务商ID
	MchId          string       `orm:"column(mch_id);size(32);null" json:"mch_id" form:"mch_id"`              //微信商户号ID
	SubAppId       string       `orm:"column(sub_app_id);size(32);null" json:"sub_app_id" form:"sub_app_id"`  //小程序的APPID
	SubMchId       string       `orm:"column(sub_mch_id);size(128);null" json:"sub_mch_id" form:"sub_mch_id"`  //子商户号
	Appkey         string       `orm:"column(appkey);type(text);null" json:"appkey" form:"appkey"`              //商户支付密钥key
	PemCert        string       `orm:"column(pem_cert);type(text);null" json:"pem_cert" form:"pem_cert"`      //支付证书公钥
	PemKey         string       `orm:"column(pem_key);type(text);null" json:"pem_key" form:"pem_key"`         //支付证书私钥
	// 备用支付参数
	CurAppId       string  `orm:"column(cur_app_id);size(32);null" json:"cur_app_id" form:"cur_app_id"`                  //当前app_id
	SecondMchId    string  `orm:"column(second_mch_id);size(32);null" json:"second_mch_id" form:"second_mch_id"`         //备用商户号ID
	SecondAppkey   string  `orm:"column(second_appkey);size(50);null" json:"second_appkey" form:"second_appkey"`         //备用支付密钥key
	SecondPemCert  string  `orm:"column(second_pem_cert);type(text);null" json:"second_pem_cert" form:"second_pem_cert"` //备用支付证书公钥
	SecondPemKey   string  `orm:"column(second_pem_key);type(text);null" json:"second_pem_key" form:"second_pem_key"`    //备用支付证书私钥
	//
	StatusId       int16        `orm:"column(status_id);null" json:"status_id" form:"status_id"`              //状态ID：-2：逻辑删除；1：有效
	UpdatedAt      time.Time    `orm:"auto_now;column(updated_at);type(datetime);null" json:"updated_at"`     //更新时间
	CreatedAt      time.Time    `orm:"auto_now_add;column(created_at);type(datetime);null" json:"created_at"` //创建时间
}

func init() {
    orm.RegisterModel(new(AcPayParams))   
}

func AddAcPayParams(m *AcPayParams) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetAcPayParamsById(id int64) (v *AcPayParams, err error) {
	o := models.GetDefaultDB()
	v = &AcPayParams{PayParamsId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAcPayParamsByAppId(appId string) (acPay *AcPayParams, err error) {
	o := models.GetDefaultDB()
	acPay = &AcPayParams{AppId: appId}   //多个的话,read中需要指明列
	if err = o.Read(acPay,"AppId"); err != nil {
		return
	}
	return
}

func GetAcPayParamsByMchId(mchId string) (acPay *AcPayParams, err error) {
	o := models.GetDefaultDB()
	acPay = &AcPayParams{MchId: mchId}   //
	if err = o.Read(acPay,"MchId"); err != nil {
		return
	}
	return
}

func GetAcPayParamsBySubMchId(subMchId string) (acPay *AcPayParams, err error) {
	o := models.GetDefaultDB()
	acPay = &AcPayParams{SubMchId: subMchId}   //
	if err = o.Read(acPay,"SubMchId"); err != nil {
		return
	}
	return
}

func GetAcPayParamsBySubAppId(subAppId string) (acPay *AcPayParams, err error) {
	o := models.GetDefaultDB()
	acPay = &AcPayParams{SubAppId: subAppId}   //多个的话,read中需要指明列
	if err = o.Read(acPay,"SubAppId"); err != nil {
		return
	}
	return
}

func GetParamsByAppIdOrSubAppId(appId string) (acPay *AcPayParams, err error) {
	o := models.GetDefaultDB()
	acPay = &AcPayParams{AppId: appId}   
	if appId == "wx204da65aa7d948b0" {
	    acPay.SubAppId = appId
		if err = o.Read(acPay, "AppId", "SubAppId"); err == nil {
			if acPay.MchTypeId == 1 {
			   return
			}
		}
	}
	if err = o.Read(acPay, "AppId"); err == nil {
		if acPay.MchTypeId != 2 {
		   return
		}
	}
	acPay.AppId = ""
	acPay.SubAppId = appId
	if err = o.Read(acPay,"SubAppId"); err == nil {
		if acPay.MchTypeId == 2 {
		   return
		}
	}
	err = errors.New("ac_pay_params is null")
	return
}

func GetParamsByAppIdOrSubAppId2(appId string) (acPay *AcPayParams, err error) {
	o := models.GetDefaultDB()
	acPay = &AcPayParams{}
	query := o.QueryTable(new(AcPayParams))
	// 特约商户类型
	err = query.Filter("sub_app_id", appId).Filter("mch_type_id", 2).One(acPay)
	if err == nil {
	   return
	}
	// 普通商户类型
	validIds :=[]string{"1","4","5"}
	err = query.Filter("app_id", appId).Filter("mch_type_id__in", validIds).One(acPay)
	if err == nil {
	   return
	}
	err = errors.New("ac_pay_params is null")
	return
}

func GetParamsByMchIdOrSubMchId(mchId string) (acPay *AcPayParams, err error) {
	o := models.GetDefaultDB()
	acPay = &AcPayParams{MchId: mchId}   
	if err = o.Read(acPay, "MchId"); err == nil {
		return
	}
	acPay.MchId = ""
	acPay.SubMchId = mchId
	if err = o.Read(acPay,"SubMchId"); err == nil {
		return
	}
	err = errors.New("ac_pay_params is null")
	return
}

func GetAcPayParamsByAppIds(mchTypeId int, appId, subAppId string) (acPay *AcPayParams, err error) {
	acPay = &AcPayParams{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(AcPayParams))
	qs = qs.Filter("app_id", appId)
	if mchTypeId == 2 {
	    qs = qs.Filter("sub_app_id", subAppId)
	}
	err = qs.One(acPay)
	return
}

func GetAllAcPayParams(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*AcPayParams, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(AcPayParams))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*AcPayParams
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, param := range lists {
			param.CustAccountId = param.CustAccount.CustAccountId
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateAcPayParamsById(m *AcPayParams, k ...string) (id int64, err error) {
	o := models.GetDefaultDB()
	v := AcPayParams{PayParamsId: m.PayParamsId}
	if err = o.Read(&v); err != nil {
		return 0, err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return 0, err
		}
		id = v.CustAccountId
	}
	return id, nil
}

func DeleteAcPayParamsById(id int64) (err error) {
	o := models.GetDefaultDB()
	v := AcPayParams{PayParamsId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

